package presentation.converters;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import persistence.Periodical;
import business.BusinessObjectAssembler;
import business.PeriodicalLogic;
import business.exception.BusinessException;

public class PeriodicalConverter implements Converter{
	private static PeriodicalLogic periodicalLogic;
	
	static {
		periodicalLogic = BusinessObjectAssembler.getPeriodicalLogic();
	}
	@Override
	public Object getAsObject(FacesContext fctx, UIComponent component, String value)
			throws ConverterException {
		List<Periodical> periodicals = null;
		Periodical retVal = null;
		
		if (value != null && ConverterUtil.isNumber(value)) {
			try {
				periodicals = periodicalLogic.getAllPeriodicals();
			}
			catch (BusinessException be) {
				
			}
			for (Periodical per : periodicals) {			
				if (per.getId() == Integer.valueOf(value)) {
					retVal = per;
				}
			}
		}
		return retVal;		
	}

	@Override
	public String getAsString(FacesContext fctx, UIComponent component, Object value)
			throws ConverterException 
	{
		String retVal = null;
		Periodical per = (Periodical) value;
		if (per != null)
			retVal = String.valueOf(per.getId());	
		return retVal;
	}
}
